import { useCallback, useEffect, useRef, useState } from "react";
import { Select, Pagination, Radio, Empty } from "antd";
import IconComponent from "@/components/custom/IconComponent";
import * as icons from "@ant-design/icons/";
import "@/styles/components/custom/iconSelect.scss";
import PropTypes from "prop-types";

const iconList = Object.keys(icons);

/**
 * 处理分页数据
 *
 * @param {Array} data
 * @param {Number} pageNum
 * @param {Number} pageSize
 * @param {Object} options
 * @returns fillData
 */
const handlePageData = (data = [], pageNum, pageSize, options) => {
  const fillData = data.filter((item) => {
    if (options.searchKey) {
      item = item.toLowerCase();
      options.type = options.type.toLowerCase();
      options.searchKey = options.searchKey.toLowerCase();
      return item.endsWith(options.type) && item.includes(options.searchKey);
    }
    return item.endsWith(options.type);
  });

  const startIndex = (pageNum - 1) * pageSize;
  let endIndex = Math.min(startIndex + pageSize, fillData.length);
  return {
    total: fillData.length,
    data: fillData.slice(startIndex, endIndex),
  };
};

const IconSelectComponent = (props) => {
  const [searchKey, setSearchKey] = useState(null);
  const [value, setValue] = useState(null);
  const ref = useRef(null);

  const onSelect = (value) => {
    ref.current.blur();
    setValue(value);
    props.onChange && props.onChange(value);
  };

  return (
    <Select
      {...props}
      showSearch
      ref={ref}
      onSearch={(value) => setSearchKey(value)}
      dropdownRender={() => <IconSelectDropdown value={value} searchKey={searchKey} onSelect={onSelect} />}
    />
  );
};

IconSelectComponent.propTypes = {
  onChange: PropTypes.func,
};

const IconSelectDropdown = ({ value, searchKey: defaultSearchKey, onSelect }) => {
  const [pageInfo, setPageInfo] = useState({ pageNum: 1, pageSize: 100, total: 0 });
  const [type, setType] = useState("Outlined");
  const [items, setItems] = useState([]);
  const ref = useRef(null);
  const searchKey = useRef(defaultSearchKey).current;

  const onInitData = useCallback(() => {
    const pageNum = pageInfo.pageNum;
    const pageSize = pageInfo.pageSize;
    const option = { searchKey, type };
    const { total, data: pageItmes } = handlePageData(iconList, pageNum, pageSize, option);
    setPageInfo({ pageNum, pageSize, total });
    setItems(pageItmes);
  }, [pageInfo.pageNum, pageInfo.pageSize, searchKey, type]);

  useEffect(() => onInitData(), [onInitData]);

  const className = "ant-select-item ant-select-item-option";
  const selectClassName = "ant-select-item ant-select-item-option ant-select-item-option-selected";

  const handleTypeChange = (value) => {
    value = value.target ? value.target.value : value;
    setType(value);
    setPageInfo({ pageNum: 1, pageSize: 100, total: 0 });
  };

  const handleSelect = (keyName) => {
    onSelect && onSelect(keyName);
  };

  return (
    <div ref={ref}>
      <div style={{ textAlign: "center", paddingBottom: "8px" }}>
        <Radio.Group onChange={handleTypeChange} value={type}>
          <Radio value="Outlined">Outlined</Radio>
          <Radio value="Filled">Filled</Radio>
          <Radio value="TwoTone">TwoTone</Radio>
        </Radio.Group>
      </div>

      <div className="icon-select-dropdown">
        {items.map((keyName) => (
          <div
            key={keyName}
            className={keyName === value ? selectClassName : className}
            onClick={(e) => handleSelect(keyName, e)}
          >
            <div className="ant-select-item-option-content">
              <div style={{ fontSize: "2em" }}>{<IconComponent value={keyName} />}</div>
              <div style={{ fontSize: "12px" }}>{keyName}</div>
            </div>
          </div>
        ))}
        {!items.length && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
      </div>

      <Pagination
        style={{ textAlign: "center", paddingTop: "8px" }}
        size="small"
        hideOnSinglePage={true}
        current={pageInfo.pageNum}
        pageSize={pageInfo.pageSize}
        total={pageInfo.total}
        showSizeChanger={false}
        onChange={(pageNum, pageSize) => setPageInfo({ pageNum, pageSize })}
      />
    </div>
  );
};

IconSelectDropdown.propTypes = {
  onSelect: PropTypes.func,
  value: PropTypes.string,
  searchKey: PropTypes.string,
};

export default IconSelectComponent;
